package edu.spangler.dang.FriendViewer;

import java.util.ArrayList;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

/**
 * The main activity for the Friend Viewer application.
 * Displays a list of available friends to pick from.
 * @author Tuan Dang
 */
public class FriendViewer extends Activity {

	private ListView friendsList;
	private TextView status;
    private Button btnShowMap;
	private FriendObject theUser;
	private ArrayList<FriendObject> friends;
	private ArrayList<String> friendNames;
	private ArrayList<Object> objs;
	
	/**
	 * Creates the a GUI screen
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		friendsList = (ListView)findViewById(R.id.listFriends);
		status = (TextView)findViewById(R.id.status);
        btnShowMap = (Button)findViewById(R.id.btnShowMap);
		
		processAndDisplay();
	}
	
	/**
	 * Method that reads data from the content provider and
	 * then sets the GUI components with data.
	 */
	@SuppressWarnings("unchecked")
	public void processAndDisplay() {		
		objs = ProcessContentProvider.process(this, true);

        if (objs.size() == 0)
        {
            status.setText("The friend tracker service has not been started.");
            btnShowMap.setEnabled(false);
        }
        else
        {
            theUser = (FriendObject)objs.get(0);
            int count = (Integer)objs.get(1);
		
            if (count == 0)
            {
                status.setText("No friends currently found on the server.");
                friends = new ArrayList<FriendObject>();
                friendNames = new ArrayList<String>();
            }
            else
            {
                status.setText(count + " friends currently on the server.");
                
                friends = (ArrayList<FriendObject>)objs.get(2);
                friendNames = (ArrayList<String>)objs.get(3);
                
                // Display the list of friends and allow each item to be clickable
                friendsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, friendNames));
                friendsList.setClickable(true);
                friendsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Log.d("FriendViewer", "Clicked on user: " + position);
                        FriendObject center = friends.get(position);
                        mapScreen(view, center.getUsername(), center.getLatitude(), center.getLongitude());
                    }
                });
            }
        }
	}
	
	/**
	 * Method that handles the show map button on the screen.
	 * Basically centers the map around the current user's location.
	 * @param view
	 */
	public void showMap(View view) {
		mapScreen(view, theUser.getUsername(), theUser.getLatitude(), theUser.getLongitude());
	}
	
	/**
	 * Method that creates an intent to start the map activity.
	 * Loads variables into the intent to center the map to as well
	 * as display the friends.
	 * @param view
	 * @param username the user's username to center on
	 * @param latitude the latitude to center the map on
	 * @param longitude the longitude to center the map on
	 */
	public void mapScreen(View view, String username, double latitude, double longitude) {
		Intent myIntent = new Intent(view.getContext(), FriendMap.class);
		myIntent.putExtra("username", username);
		myIntent.putExtra("centerLatitude", latitude);
		myIntent.putExtra("centerLongitude", longitude);
		//myIntent.putExtra("friends", getFriends().toArray());
		myIntent.putExtra("friends", friends.toArray(new FriendObject[friends.size()]));
		startActivity(myIntent);
	}

	/**
	 * A Broadcast Receiver that listens for a content provider changed
	 * action. Will update the GUI to reflect said changes.
	 */
	private BroadcastReceiver friendReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			processAndDisplay();
		}
	};
	
	/**
	 * Method where when the FriendViewer activity is resumed, will
	 * set up the Broadcast Receiver and refresh the GUI for any changes.
	 */
	public void onResume() {
		super.onResume();
		
		IntentFilter filter = new IntentFilter();
		filter.addAction("edu.spangler.dang.FriendsUpdated");
		
		this.registerReceiver(this.friendReceiver, filter);
		processAndDisplay();
	}
	
	/**
	 * Method that will turn off the Broadcast Receiver when FriendViewer
	 * activity is paused.
	 */
	public void onPause() {
		super.onPause();
		
		this.unregisterReceiver(this.friendReceiver);
	}
}